package com.liyl.controller;

import com.liyl.service.DaleTouService;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;

@Controller
@RequestMapping("daletou")
public class DaleTouController {

    @Autowired
    private DaleTouService daleTouService;

    @RequestMapping("kai")
    public String daletou(Model model) {

        String str = daleTouService.lottery();
        model.addAttribute("contents", str);
        return "index";
    }

    @RequestMapping("/download")
    public void download(String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取upload文件夹的路径
        String realPath = request.getRealPath("D:/dcache/");
        //通过流读取文件
        FileInputStream is = new FileInputStream(new File(realPath, fileName));
        //获得响应流
        ServletOutputStream os = response.getOutputStream();
        //设置响应头信息
        response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
        //通过响应流将文件输入流读取到的文件写出
        IOUtils.copy(is, os);
        //关闭流
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }
}
